<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>MQTT主机 - 物联网调试管理系统</title>
    <script th:src="@{/statics/jquery-1.12.4.min.js}"></script>
    <script th:src="@{/statics/tabler/tabler.min.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/tabler/tabler.min.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/statics/bootstrap/table/bootstrap-table.min.css}">
    <script th:src="@{/statics/bootstrap/table/bootstrap-table.min.js}"></script>
    <script th:src="@{/statics/bootstrap/table/bootstrap-table-zh-CN.min.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/system/common.css}">
    <script th:src="@{/statics/layer/layer.js}"></script>
    <script th:src="@{/statics/system/common.js}"></script>
    <script th:src="@{/statics/system/utils.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/layui/layui.css}" />
    <script th:src="@{/statics/layui/layui.js}"></script>
</head>
<body>
<div class="page">
    <div th:replace="common/header :: header"></div>

    <div class="page-wrapper">
        <div class="page-header d-print-none">
            <div class="container-xl">
                <div class="row g-2 align-items-center">
                    <div class="col">
                        <div class="page-pretitle">
                            物联网调试管理后台
                        </div>
                        <h2 class="page-title">
                            MQTT主机管理
                        </h2>
                    </div>
                    <div class="col-auto ms-auto d-print-none">
                        <div class="btn-list">
                            <button onclick="addToken()" class="layui-btn layui-btn-primary">
                                添加主机
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-body">
            <div class="container-xl">
                <div class="row row-deck row-cards">
                    <div class="col-12">
                        <div id="card" class="card">
                            <div class="card-body">
                                <table id="token_list" class="layui-table" lay-filter="tokenTable"></table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加MQTT主机内容 -->
    <div id="modal-add" style="display: none;">
        <div class="layui-form" style="padding: 20px;">
            <div class="layui-form-item">
                <label class="layui-form-label">主机名称</label>
                <div class="layui-input-block">
                    <input id="add_name" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">Token</label>
                <div class="layui-input-block">
                    <div class="layui-input-inline">
                        <input id="add_token" type="text" class="layui-input">
                    </div>
                    <button id="add_resettoken" class="layui-btn" type="button">生成</button>
                </div>


            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT连接协议</label>
                <div class="layui-input-block">
                    <select id="add_mqtt_protocol" class="layui-select">
                        <option value="0">ws:// (默认8083)</option>
                        <option value="1">mqtt:// (默认1883)</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器地址</label>
                <div class="layui-input-block">
                    <input id="add_mqtt_server" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器端口</label>
                <div class="layui-input-block">
                    <input id="add_mqtt_port" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器用户名</label>
                <div class="layui-input-block">
                    <input id="add_mqtt_username" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器密码</label>
                <div class="layui-input-block">
                    <input id="add_mqtt_password" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button onclick="submitAdd()" class="layui-btn" id="add_save">保存</button>
                    <button class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑MQTT主机内容 -->
    <div id="modal-edit" style="display: none;">
        <div class="layui-form" style="padding: 20px;">
            <input type="hidden" id="edit_id">
            <div class="layui-form-item">
                <label class="layui-form-label">主机名称</label>
                <div class="layui-input-block">
                    <input id="edit_name" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">Token</label>
                <div class="layui-input-inline">
                    <input readonly id="edit_token" type="text" class="layui-input">
                </div>
                <button id="edit_resettoken" class="layui-btn" type="button">生成</button>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT连接协议</label>
                <div class="layui-input-block">
                    <select id="edit_mqtt_protocol" class="layui-select">
                        <option value="0">ws:// (默认8083)</option>
                        <option value="1">mqtt:// (默认1883)</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器地址</label>
                <div class="layui-input-block">
                    <input id="edit_mqtt_server" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器端口</label>
                <div class="layui-input-block">
                    <input id="edit_mqtt_port" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器用户名</label>
                <div class="layui-input-block">
                    <input id="edit_mqtt_username" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">MQTT服务器密码</label>
                <div class="layui-input-block">
                    <input id="edit_mqtt_password" type="text" class="layui-input" />
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button onclick="submitEdit()" class="layui-btn" id="edit_save">保存</button>
                    <button class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script th:inline="none">
    //菜单class追加属性
    $(function () {
        $("#menu_nmqs").addClass("active");
    });

    layui.use(['table', 'layer', 'form'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;

        table.render({
            elem: '#token_list',
            url: '/nmqs/list',
            method: 'GET',
            page: true,
            request: {
                pageName: "pageNum",
                limitName: "pageSize",
            },
            parseData: function (res) {
                return {
                    code: res.code === 200 ? 0 : 1,
                    msg: res.msg,
                    count: res.data.total,
                    data: res.data.rows,
                };
            },
            cols: [[
                {field: 'id', title: 'ID', align: 'center', width: 50},
                {field: 'name', title: '主机名称', align: 'center', width: 200},
                {field: 'token', title: 'Token', align: 'center', width: 200},
                {field: 'protocol', title: '协议', align: 'center', width: 100, templet: function(d) {
                        return d.protocol === 0 ? '<span class="layui-badge layui-bg-green">ws://</span>' : '<span class="layui-badge layui-bg-green">mqtt://</span>';
                    }},
                {field: 'mqttServer', title: '服务器', align: 'center', templet: function(d) {
                        return d.mqttServer + ":" + d.mqttPort;
                    }},
                {field: 'operate', title: '操作', align: 'center', width: 200, toolbar: '#operationBar'}
            ]]
        });

        table.on('tool(tokenTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'show'){
                showInfo(data.id);
            } else if(obj.event === 'edit'){
                editInfo(data.id);
            } else if(obj.event === 'delete'){
                deleteToken(data.id);
            }
        });

        $('#add_resettoken').on('click', function () {
            $("#add_token").val(randomString(12));
        });

        $('#edit_resettoken').on('click', function () {
            $("#edit_token").val(randomString(12));
        });

        window.addToken = function() {
            layer.open({
                type: 1,
                title: '添加MQTT主机',
                area: ['600px', '500px'],
                content: $('#modal-add'),
                success: function(layero, index){
                    form.render();
                }
            });
        };

        window.showInfo = function(id) {
            $.ajax({
                url: "/nmqs/info/" + id,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    var params = data.data;
                    layer.open({
                        type: 1,
                        title: '主机详情',
                        area: ['600px', '400px'],
                        content: '<div class="layui-form" style="padding: 20px;">' +
                            '<div class="layui-form-item"><label class="layui-form-label">连接协议</label><div class="layui-input-block"><span class="layui-badge layui-bg-green">' + (params.protocol===0?"ws://":"mqtt://") + '</span></div></div>' +
                            '<div class="layui-form-item"><label class="layui-form-label">服务器地址</label><div class="layui-input-block">' + params.mqttServer + '</div></div>' +
                            '<div class="layui-form-item"><label class="layui-form-label">端口</label><div class="layui-input-block">' + params.mqttPort + '</div></div>' +
                            '<div class="layui-form-item"><label class="layui-form-label">用户名</label><div class="layui-input-block">' + params.mqttUsername + '</div></div>' +
                            '<div class="layui-form-item"><label class="layui-form-label">密码</label><div class="layui-input-block">' + params.mqttPassword + '</div></div>' +
                            '</div>'
                    });
                }
            });
        };

        window.editInfo = function(id) {
            $.ajax({
                url: "/nmqs/info/" + id,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    var params = data.data;
                    layer.open({
                        type: 1,
                        title: '编辑MQTT主机',
                        area: ['600px', '500px'],
                        content: $('#modal-edit'),
                        success: function(layero, index){
                            var editForm = layero.find('.layui-form');
                            editForm.find('#edit_id').val(params.id);
                            editForm.find('#edit_name').val(params.name);
                            editForm.find('#edit_token').val(params.token);
                            editForm.find('#edit_mqtt_protocol').val(params.protocol);
                            editForm.find('#edit_mqtt_server').val(params.mqttServer);
                            editForm.find('#edit_mqtt_port').val(params.mqttPort);
                            editForm.find('#edit_mqtt_username').val(params.mqttUsername);
                            editForm.find('#edit_mqtt_password').val(params.mqttPassword);
                            form.render();
                        }
                    });
                }
            });
        };

        window.submitAdd = function() {
            const fields = [
                { selector: "#add_name", message: "主机名称不能为空" },
                { selector: "#add_token", message: "Token不能为空" },
                { selector: "#add_mqtt_protocol", message: "协议不能为空" }
            ];

            for (const field of fields) {
                if (isBlank($(field.selector).val())) {
                    layer.msg(field.message);
                    return;
                }
            }

            let data = {
                name: $("#add_name").val(),
                token: $("#add_token").val(),
                protocol: $("#add_mqtt_protocol").val(),
                mqttServer: $("#add_mqtt_server").val(),
                mqttPort: $("#add_mqtt_port").val(),
                mqttUsername: $("#add_mqtt_username").val(),
                mqttPassword: $("#add_mqtt_password").val()
            };

            $.post({
                url: "/nmqs/add",
                dataType: "json",
                data: JSON.stringify(data),
                contentType:'application/json;charset=UTF-8',
                success: function (data) {
                    if (data.code === 200) {
                        layer.msg("添加成功");
                        layer.closeAll();
                        layui.table.reload('token_list');
                    } else {
                        layer.msg(data.msg);
                    }
                }
            });
        };

        window.submitEdit = function() {
            const fields = [
                { selector: "#edit_token", message: "Token不能为空" },
                { selector: "#edit_name", message: "名称不能为空" },
                { selector: "#edit_mqtt_protocol", message: "协议不能为空" }
            ];

            for (const field of fields) {
                if (isBlank($(field.selector).val())) {
                    layer.msg(field.message);
                    return;
                }
            }

            let data = {
                id: $("#edit_id").val(),
                name: $("#edit_name").val(),
                token: $("#edit_token").val(),
                protocol: $("#edit_mqtt_protocol").val(),
                mqttServer: $("#edit_mqtt_server").val(),
                mqttPort: $("#edit_mqtt_port").val(),
                mqttUsername: $("#edit_mqtt_username").val(),
                mqttPassword: $("#edit_mqtt_password").val()
            };

            layer.confirm('你确认要修改 ID:'+data.id+' 吗？', {
                btn: ['确认','取消']
            }, function(){
                $.post({
                    url: "/nmqs/update",
                    dataType: "json",
                    data: JSON.stringify(data),
                    contentType:'application/json;charset=UTF-8',
                    success: function (data) {
                        if (data.code === 200) {
                            layer.msg("修改成功");
                            layer.closeAll();
                            layui.table.reload('token_list');
                        } else {
                            layer.msg(data.msg);
                        }
                    }
                });
            }, function(){
                layer.msg('已取消');
            });
        };

        window.deleteToken = function(id){
            let url = "/nmqs/delete/" + id;

            layer.confirm('你确认要删除 ID:'+id+' 吗？', {
                btn: ['确认','取消']
            }, function(){
                $.ajax({
                    url: url,
                    type: "POST",
                    dataType: "json",
                    success: function (data) {
                        if (data.code === 200) {
                            layui.table.reload('token_list');
                            layer.msg('删除成功！', {icon: 1});
                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }
                    }
                });
            }, function(){
                layer.msg('已取消', {icon: 1});
            });
        };
    });

    function randomString(length) {
        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var result = '';
        for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }

    function isBlank(str) {
        return (!str || /^\s*$/.test(str));
    }
</script>
<script type="text/html" id="operationBar">
    <a class="layui-btn layui-btn-xs" lay-event="show">查看</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<style>
    .layui-form-label {
        width: 100px;
    }
</style>
</html>
